# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/5/22 09:14
@Description: 赶集网 图片验证码
"""
import requests
from fake_useragent import UserAgent
import re
from lxml import etree
import json

# from PIL import Image
# import pytesseract
# from YDM import get_code
from chao_ji_ying_client import Chaojiying_Client


def get_image(session, response):
    tree = etree.HTML(response)
    image_url = tree.xpath("//*[@id=\"login-content\"]/div/div/div[1]/div[2]/form[1]/div[4]/label/img/@data-url")[0]
    image_response = session.get(image_url)
    with open("verify_code.jpg", "wb") as f:
        f.write(image_response.content)


if __name__ == '__main__':
    login_url = "https://passport.ganji.com/login.php"
    headers = {"User-Agent": UserAgent().random}
    # headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4157.4 Safari/537.36"}
    session = requests.Session()

    login_response = session.get(login_url)
    get_image(session, login_response.text)

    # pytesseract 识别验证码
    # image = Image.open("./verify_code.jpg")
    # code = pytesseract.image_to_string(image)

    # 云打码 识别验证码
    # code = get_code("verify_code.jpg")

    # 超级鹰平台 识别验证码
    username = "thekernel"
    password = "Kernel990621"
    soft_id = "ab35607581d4ae6281c720e4f39cfd9b"
    chaojiying = Chaojiying_Client(username, password, soft_id)
    im = open('verify_code.jpg', 'rb').read()
    result = chaojiying.PostPic(im, 1902)
    # {
    #     'err_no': 0,
    #     'err_str': 'OK',
    #     'pic_id': '9105909594337300001',
    #     'pic_str': 'ang5',
    #     'md5': '06f5c29f9c5915375157abf44c3f1bd5'
    # }
    code = result["pic_str"]

    hash_code = re.findall("\"__hash__\":\"(.+)\"", login_response.text)[0]

    form_data = dict({
        "username": "17342019665",
        "password": "Kernel990621",
        "setcookie": "14",
        "checkCode": code,
        "__hash__": hash_code,
        "source": "passport"
    })

    res = session.post(login_url, data=form_data, headers=headers)
    data = json.loads(res.text[1: -1])
    # print(data)
    # {
    #     'site_id': 1,
    #     'status': 1,
    #     'user_id': 812652029,
    #     'sscode': 'v3FNo1ZlG9dZDMDcv3avg2LR',
    #     'cookie_expire': 1591841568,
    #     'site_list': {
    #         '5': {
    #             'cookie_domain': 'ganji.com.cn',
    #             'host': 'http://sync.ganji.com.cn',
    #             'login_url': 'passport/sync.php',
    #             'logout_url': 'passport/sync.php',
    #             'site_id': 5
    #         }
    #     },
    #     'next': 'http://www.ganji.com/user/login_success.php?username=17342019665'
    # }
    new_url = data["next"]
    new_res = session.get(new_url)
    # print(new_res.text)
    if "thekernelz" in new_res.text:
        print("登录成功")
